package com.ssh.cp.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.ssh.cp.entity.FileEntity;
import com.ssh.cp.iservice.IFileService;
import com.ssh.cp.util.FileUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;





@Controller
public class FileAction{
	@Autowired
	private IFileService fileService;
	
	private int classid,libraryid;
	
    private File file;
    
    private int fileid;
    
    private FileEntity upload_file,update;
    
    private JSONObject result;//用作Json结果
    
    private JSONObject fileclass;//用作文件类型的Json结果

	private ActionContext ctx;
	
    // 封装上传文件类型的属性
    private String fileContentType;
    // 封装上传文件名的属性
    private String fileFileName;
    // 接受依赖注入的属性
    private String userPath;
    
    //文件下载名
    private String dl_fileName;
	
    private InputStream fileInputStream;
    
    private int draw , recordsTotal, recordsFiltered,start,length;//用于返回给JQueryDatatables 数据参数
    
    private String search;//搜索关键字

    private String formername;//文件原文件名
	


	//文件上传
	public String uploadFile() throws IOException {
		ctx=ActionContext.getContext();
		userPath=ctx.getSession().get("username")+File.separator;
		int userid=Integer.valueOf(ctx.getSession().get("userid").toString());
		if(file==null) {
			return "fail";
		}else {
		
		String savePath=FileUtil.DEFAULT_FILE_SAVEPATH+userPath;
		
		System.out.println("========Share: "+upload_file.getShare());
				
		System.out.println("========download: "+upload_file.getDownload());
		//fileService.saveFile(getFileFileName(),savePath); //文件信息存入数据库
		System.out.println("========fileFileName: "+fileFileName);
		
		System.out.println("========userid:  "+userid);
		
		
		
		upload_file.setFilename(fileFileName);
		upload_file.setSavepath(savePath);		
//		upload_file.setShare(share);
//		upload_file.setDownload(download);
		
//		upload_file.setClassid(classid);
//		upload_file.setLibraryid(libraryid);
		
//		upload_file.setUserid(userid);
		
		fileService.doFileSave(file, upload_file);
		return "success";
		}
	}
	
	



	/*
	 * 
	 * 列出物理文件，将result作为JSONObject
	 * 
	 * 暂时不用。。。
	 */
	public String listFile() {
		ctx=ActionContext.getContext();
		System.out.println("username"+ctx.getSession().get("username"));
		//userPath=FileUtil.DEFAULT_FILE_SAVEPATH+ctx.getSession().get("username")+File.separator;
		userPath=FileUtil.DEFAULT_FILE_SAVEPATH;
		File userFile=new File(userPath);
		File[] f=userFile.listFiles();		
		JSONArray array = new JSONArray();
		result=new JSONObject();
		for(int i=0;i<f.length;i++) {
			JSONObject json =new JSONObject();
			json.put("filename", f[i].getName());
			array.add(json);
		}
		
		result.put("data",array);
		
		//setResult(json.toString());
		//result="hi!";
		return "success";
	}
	
	/*
	 * 列出文件的数据库信息
	 * 普通用户使用
	 * 后台分页
	 * */
	public String listFile1() {
		ctx=ActionContext.getContext();
		/*
		System.out.println("========start: "+start);		
		System.out.println("========length: "+length);
		System.out.println("========draw:"+draw);
		System.out.println("========count:"+fileService.getCount());
		System.out.println("========search:  "+getSearch());
		*/
		List<?> list=null;
		int userid=Integer.valueOf(ctx.getSession().get("userid").toString());
		recordsTotal=fileService.getCount(userid);
		if (search == null || "".equals(search) || "undefine".equals(search)) {
			recordsFiltered = recordsTotal;
			list = fileService.listFileByUserId(userid, start, length);
		} else {
			list = fileService.listFileByFileName(userid, search, start, length);
			recordsFiltered = list.size();
		}

		result=new JSONObject();
		result.put("draw",draw);
		result.put("recordsTotal",recordsTotal);
		result.put("recordsFiltered",recordsFiltered);
		
		JSONArray array =JSONArray.fromObject(list);		
		
		result.put("data",array);
		
		return "success";
	}
/*
 * 列出用户所有文件，前台分页
 * 
 */
	public String listFile3() {
		ctx=ActionContext.getContext();
		List<?> list=null;
		int userid=Integer.valueOf(ctx.getSession().get("userid").toString());
		list=fileService.listAllUserFile(userid);
		result=new JSONObject();
		JSONArray array =JSONArray.fromObject(list);		
		result.put("data",array);
		return "success";
	}
	
	
	
	public String listShareFile() {
		List<?> list=fileService.listShareFile(start, length);
		recordsTotal=fileService.getShareFileNum();
		recordsFiltered = recordsTotal;
		
		if (search == null || "".equals(search) || "undefine".equals(search)) {
			recordsFiltered = recordsTotal;
			list = fileService.listShareFile(start, length);
		} else {
			list = fileService.listShareFile(search, start, length);
			recordsFiltered = list.size();
		}
		
		
		result=new JSONObject();
		result.put("draw",draw);
		result.put("recordsTotal",recordsTotal);
		result.put("recordsFiltered",recordsFiltered);
		
		JSONArray array =JSONArray.fromObject(list);		
		
		result.put("data",array);
		
		return "success";
	}
	

/*
 * 文件下载
 * */
	public String fileDownload() throws IOException{
		ctx=ActionContext.getContext();
        String path = FileUtil.DEFAULT_FILE_SAVEPATH;
        path+=ctx.getSession().get("username");
        path+=File.separator+dl_fileName;
        //dl_fileName="Kurumi.jpg";
        System.out.println("=========dl_fileName:  "+ctx.getSession().get("username"));
        System.out.println("=========dl_fileName:"+path);
        
        File dlFile=new File(path);
        if(dlFile.exists()) {
        	setFileInputStream(new FileInputStream(dlFile));
        	return "success";	
        }else {
        	@SuppressWarnings("unchecked")
			Map<String, Object> request=(Map<String, Object>)ctx.get("request");
        	request.put("tip", "文件下载失败");
        	return "fail";
        }
    }
	
	public String sharedFileDownload() throws IOException{
		ctx=ActionContext.getContext();
		File sfd=fileService.sharedFileDownload(fileid);
		
		if(sfd!=null&&sfd.exists()) {
			dl_fileName=sfd.getName();
			fileInputStream=new FileInputStream(sfd);
        	return "success";	
		}else {
			@SuppressWarnings("unchecked")
			Map<String, Object> request=(Map<String, Object>)ctx.get("request");
        	request.put("tip", "文件下载失败或文件不允许下载");
        	return "fail";
		}
	}
	
	
	public String listFileClass() {
		fileclass=new JSONObject();
		List<?> list=fileService.listFileClass();
		JSONArray classarray=JSONArray.fromObject(list);
		fileclass.put("fileclass", classarray);
		
		return "success";
	}
	
	public String updateFile() {
		ctx=ActionContext.getContext();
		
        String oldfile = FileUtil.DEFAULT_FILE_SAVEPATH;
        System.out.println("=========Fileid:  "+update.getFileid());
        oldfile+=ctx.getSession().get("username");
        String newfile =oldfile+File.separator+update.getFilename();
        oldfile+=File.separator+getFormername();
        System.out.println("=========formername:  "+formername);
        System.out.println("=========oldfile:  "+oldfile);
        System.out.println("=========newfile:"+newfile);
        System.out.println("=========share:"+update.getClassid());
        System.out.println("=========down:"+update.getLibraryid());
       
        if(fileService.doFileUpdate(oldfile, newfile, update))
        	return "success";
        else
        	return "fail";

	}
	
	public String ZipFile() throws FileNotFoundException {
		ctx=ActionContext.getContext();
		String userPath = FileUtil.DEFAULT_FILE_SAVEPATH;        
        userPath+=ctx.getSession().get("username");
        
        File zipFile=fileService.downloadAll(userPath);
        if(zipFile.exists()) {
        	
        	fileInputStream=new FileInputStream(zipFile);
        	return "success";
        }
        else
        	return "fail";
	}
	

	
	
	
	
	
	
	
	public File getFile() {
		return file;
	}


	public void setFile(File file) {
		this.file = file;
	}


	public String getFileContentType() {
		return fileContentType;
	}


	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}


	public String getFileFileName() {
		return fileFileName;
	}


	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}


	public String getUserPath() {
		return userPath;
	}


	public void setUserPath(String userPath) {
		this.userPath = userPath;
	}


	public IFileService getFileService() {
		return fileService;
	}


	public void setFileService(IFileService fileService) {
		this.fileService = fileService;
	}


	

	public int getClassid() {
		return classid;
	}


	public void setClassid(int classid) {
		this.classid = classid;
	}



	public int getLibraryid() {
		return libraryid;
	}


	public void setLibraryid(int libraryid) {
		this.libraryid = libraryid;
	}

	public JSONObject getResult() {
		return result;
	}

	public void setResult(JSONObject result) {
		this.result = result;
	}


	public String getDl_fileName() {
		return dl_fileName;
	}


	public void setDl_fileName(String dl_fileName) {
		this.dl_fileName = dl_fileName;
	}


	public InputStream getFileInputStream() {
		return fileInputStream;
	}


	public void setFileInputStream(InputStream fileInputStream) {
		this.fileInputStream = fileInputStream;
	}

	public int getDraw() {
		return draw;
	}


	public void setDraw(int draw) {
		this.draw = draw;
	}


	public int getRecordsTotal() {
		return recordsTotal;
	}


	public void setRecordsTotal(int recordsTotal) {
		this.recordsTotal = recordsTotal;
	}


	public int getRecordsFiltered() {
		return recordsFiltered;
	}


	public void setRecordsFiltered(int recordsFiltered) {
		this.recordsFiltered = recordsFiltered;
	}

	public String getSearch() {
		return search;
	}


	public void setSearch(String search) {
		this.search = search;
	}


	public int getStart() {
		return start;
	}


	public void setStart(int start) {
		this.start = start;
	}


	public int getLength() {
		return length;
	}


	public JSONObject getFileclass() {
		return fileclass;
	}


	public void setFileclass(JSONObject fileclass) {
		this.fileclass = fileclass;
	}


	public void setLength(int length) {
		this.length = length;
	}

	public FileEntity getUpload_file() {
		return upload_file;
	}


	public void setUpload_file(FileEntity upload_file) {
		this.upload_file = upload_file;
	}





	public FileEntity getUpdate() {
		return update;
	}





	public void setUpdate(FileEntity update) {
		this.update = update;
	}





	public String getFormername() {
		return formername;
	}





	public void setFormername(String formername) {
		this.formername = formername;
	}





	public int getFileid() {
		return fileid;
	}





	public void setFileid(int fileid) {
		this.fileid = fileid;
	}
 
}

